import { BulletDirection, PlaneCamp } from "../Constant/Constant"
import BulletControl from "../Control/BulletControl"

/**
 * 子弹工厂类（静态单例）
 * 创建子弹，并且内部使用对象池缓存
 */
export default class BulletByEnemyFactory {

    private static _prefab: cc.Prefab = null
    private static _pool: cc.NodePool = new cc.NodePool()

    /**
     * 初始化子弹工厂，设置预制体
     * @param prefab 敌机子弹预制体
     * @param size 默认对象池容量（预先创建子弹对象）
     */
    public static init(prefab: cc.Prefab, size: number = 0) {
        if (size < 0) { new Error('size不能小于0') }

        this._pool.clear()
        this._prefab = prefab

        // 初始化对象池容量
        if (size > 0) {
            for (let i = 0; i < size; i++) {
                this._pool.put(cc.instantiate(this._prefab))
            }
        }
    }

    /**
     * 创建子弹
     * @param enemyNode 敌机节点，用在敌机前方生成子弹
     * @param speed 子弹速度
     */
    public static create(enemyNode: cc.Node, speed: number = 400): cc.Node {
        let bulletNode: cc.Node = null
        if (this._pool.size() > 0) {
            bulletNode = this._pool.get()
            console.log(`[BulletByEnemyFactory] get from the pool`)
        } else {
            bulletNode = cc.instantiate(this._prefab)
            console.log(`[BulletByEnemyFactory] get from the cc.instantiate()`)
        }

        // 初始子弹位置和数据
        bulletNode.name = this._prefab.name
        if (enemyNode.parent) {
            bulletNode.setParent(enemyNode.parent)
        }
        const comp = bulletNode.getComponent(BulletControl)
        comp.init(PlaneCamp.ENEMY, BulletDirection.DOWN)
        return bulletNode
    }

    /**
     * 回收子弹
     * @param node 
     */
    public static recycle(node: cc.Node) {
        node.removeFromParent()
        if (node.name != this._prefab.name) {
            console.warn(`[BulletByEnemyFactory] 拒绝回收节点。因为回收的node节点不是由this._prefab创建的`)
            return
        }
        this._pool.put(node)
    }
}